package com.zcily.demo.config;

import com.zcily.demo.entity.dto.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestControllerAdvice
public class ValidateExceptionConfig {

    /**
     * 表单对象上的异常处理
     */
    @ExceptionHandler(BindException.class)
    public Result validExceptionHandler(BindException exception) {
        List<ObjectError> errors = exception.getAllErrors();
        String errorMessages = errors.stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining("；"));
        return Result.error("数据校验失败：" + errorMessages);
    }

    /**
     * RequestBody 上的异常处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
        List<FieldError> errors = exception.getBindingResult().getFieldErrors();
        String errorMessages = errors.stream().map(FieldError::getDefaultMessage).collect(Collectors.joining("；"));
        return Result.error("数据校验失败：" + errorMessages);
    }

    /**
     * RequestParam 和 PathVariable 上的异常处理
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result handleConstraintViolationException(ConstraintViolationException exception) {
        Set<ConstraintViolation<?>> errors = exception.getConstraintViolations();
        String errorMessages = errors.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining("；"));
        return Result.error("数据校验失败：" + errorMessages);
    }
}
